<template>
  <div class="list-wrapper">
    <!-- 联系人列表 -->

    <van-contact-list :list="list" @add="onAdd" @edit="onEdit" />
    <!-- 联系人编辑 -->
    <van-popup v-model="showEdit" position="bottom">
      <van-contact-edit
        :contact-info="editingContact"
        :is-edit="isEdit"
        @save="onSave"
        @delete="onDelete"
      />
    </van-popup>
    <!-- <ul>
      <li v-for="(item, index) in listData"><span>{{index + 1}}、</span>{{item.title}}</li>
    </ul>-->
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "contactList",
  components: {},
  props: {},
  data() {
    return {
      listData: [],
      list: [],
      instance: null, // axios 实例
      showEdit: false, // 编辑弹窗的显隐
      editingContact: {}, // 正在编辑的联系人数据
      isEdit: false // 新建或编辑
    };
  },
  watch: {},
  computed: {},
  methods: {
    // 获取本地 static 文件夹数据
    getData() {
      axios.get("/static/data/list.json").then(res => {
        // console.log(res);
        if (res.data.length > 0) {
          this.listData = res.data.slice(0);
        }
      });
    },
    // 获取 list 数据
    async getList() {
      let res = await this.$Http.getContactList();
      this.list = res.data;
    },
    // 添加联系人
    onAdd() {
      this.showEdit = true;
      this.isEdit = false;
    },
    // 编辑联系人
    onEdit(item) {
      this.showEdit = true;
      this.isEdit = true;
      this.editingContact = item;
    },
    // 保存联系人
    async onSave(item) {
      if (this.isEdit) {
        // 编辑保存
        let res = await this.$Http.editContact(item);
        if (res.code == 200) {
          this.$toast("编辑成功");
          this.showEdit = false;
          this.getList();
        }
      } else {
        // 新建保存
        // let res = await this.$Http.newContactJson(item);
        let res = await this.$Http.newContactForm(item, true);
        if (res.code == 200) {
          this.$toast("新建成功");
          this.showEdit = false;
          this.getList();
        }
      }
    },
    // 删除联系人
    async onDelete(item) {
      let res = await this.$Http.delContact({id: item.id});
      if (res.code == 200) {
        this.$toast("删除成功");
        this.showEdit = false;
        this.getList();
      }
    }
  },
  created() {
    this.getData();
  },
  mounted() {
    this.getList();
  }
};
</script>
<style lang="scss" scoped>
.list-wrapper {
  ul > li {
    padding: 0 20px;
    line-height: 60px;
    font-size: 28px;
  }
}
</style>